package cn.wolfcode.exception;

import cn.wolfcode.qo.JsonResult;
import com.alibaba.fastjson.JSON;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@ControllerAdvice
public class MyControllerAdvice {

    @ExceptionHandler(RuntimeException.class)
    public String handle(Exception e, HttpServletResponse response, HandlerMethod method) {
        e.printStackTrace();
        if (!method.hasMethodAnnotation(ResponseBody.class)) {
            return "/common/error";
        }else {
            response.setContentType("/application/json;charset=utf-8");
            JsonResult jsonResult = new JsonResult(false, "系统错误");
            try {
                response.getWriter().println(JSON.toJSONString(jsonResult));
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return null;
    }

    @ExceptionHandler(LogicException.class)
    @ResponseBody
    public JsonResult handle2(LogicException e) {
        return new JsonResult(false, e.getMessage());
    }
}
